{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "efa0e0ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.datasets import fetch_lfw_people\n",
    "import matplotlib.pyplot as plt\n",
    "data_home = \"D:\\\\ml-02\\\\03_dataset\\\\item7\"\n",
    "faces=fetch_lfw_people(min_faces_per_person=60)\n",
    "x,y=faces.data,faces.target\n",
    "target_names=faces.target_names\n",
    "n_samples,h,w=faces.images.shape\n",
    "print(target_names)\n",
    "print(n_samples,h,w)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e15d6487",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.decomposition import PCA\n",
    "n_components=150\n",
    "pca=PCA(n_components=n_components,svd_solver='randomized',whiten=True,random_state=70).fit(x)\n",
    "eigenfaces=pca.components_.reshape((n_components,h,w))\n",
    "x_pca=pca.transform(x)\n",
    "fig,ax=plt.subplots(3,5)\n",
    "for i,axi in enumerate(ax.flat):\n",
    "    axi.imshow(eigenfaces[i].reshape(h,w),cmap='bone')\n",
    "    axi.set(xticks=[],yticks=[])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14d4f806",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.svm import SVC\n",
    "from sklearn.model_selection import GridSearchCV \n",
    "from sklearn.metrics import classification_report\n",
    "from sklearn.model_selection import train_test_split\n",
    "import numpy as np\n",
    "x_train,x_test,y_train,y_test=train_test_split(x_pca,y,\n",
    "test_size=400,random_state=42)\n",
    "param_grid={'C':[1,5,10,50,100],'gamma':[0.0001,0.0005,0.001,0.005,0.01,0.1]}\n",
    "grid=GridSearchCV(SVC(kernel=\"rbf\",random_state=0),\n",
    "param_grid=param_grid,cv=5)\n",
    "grid.fit(x_train,y_train)\n",
    "print(\"最优参数值为：%s\"%grid.best_params_)\n",
    "model=grid.best_estimator_\n",
    "pred=model.predict(x_test)\n",
    "re=classification_report(y_test,pred,target_names=faces.target_names)\n",
    "print(\"最优模型的评估报告：\")\n",
    "print(re)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dbcf4279",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,ax=plt.subplots(4,6)\n",
    "for i,axi in enumerate(ax.flat):\n",
    "   axi.imshow(eigenfaces[i].reshape(h,w),cmap='bone')\n",
    "   axi.set(xticks=[],yticks=[])\n",
    "   box=dict(fc='black',alpha=0.4)\n",
    "   axi.set_ylabel(faces.target_names[pred[i]].split()[-1],\n",
    "   bbox=None if pred[i]==y_test[i] else box)\n",
    "plt.rcParams['font.sans-serif']='Simhei'\n",
    "plt.suptitle('预测名人的姓名（加边框的名字表示预测错误）',size=10)\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
